package com.info.zhiduoduo.admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alipay.api.response.AlipayDataBillBalanceQueryResponse;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyPayType;
import com.info.zhiduoduo.common.utils.LogUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.dto.alipay.AlipayAccountQueryFormBean;
import com.info.zhiduoduo.core.dto.alipay.AlipayTransferQueryFormBean;
import com.info.zhiduoduo.core.dto.pingan.BalanceQuery;
import com.info.zhiduoduo.core.dto.pingan.PinganQueryFormBean;
import com.info.zhiduoduo.core.service.WxMessageService;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BalanceService {

    @Resource
    ZddUrlConfig zddUrlConfig;

    @Resource
    PayConfig payConfig;

    @Resource
    WxMessageService wxMessageService;

    public void queryBalanceAndNotice(int type) {
        LogUtil.info("----------余额查询！----------");
//        BigDecimal balanceOne = queryDeShiJiuGeBalance();
//        BigDecimal balanceTwo = queryDeShiWuShengBalance();
//        BigDecimal balanceThree = queryChuanHuaWuShengBalance();
//        BigDecimal balanceFour = queryDeShiZhiShengBalance();
//        BigDecimal balanceFive = queryDeShiXinShengBalance();
        BigDecimal balanceEight = queryZhaoShangJiuGeBalance();
        BigDecimal balanceNine = queryZhaoShangXinShengBalance();
        BigDecimal balanceTen = queryZhaoShangZhiShengBalance();
//        BigDecimal balanceEleven = queryZhaoShangFaShengBalance();
        BigDecimal mingShengBanlance = queryZhaoShangBalance(14);
        BigDecimal meiShengBalance = queryZhaoShangBalance(16);
        BigDecimal xiuShengBalance = queryZhaoShangBalance(15);
        BigDecimal yingShengBalance = queryZhaoShangBalance(17);
        LogUtil.info("----------查询结束！----------");
        //获取到的余额
//        LogUtil.info("得仕九歌余额：" + balanceOne.toString());
//        LogUtil.info("得仕武圣余额：" + balanceTwo.toString());
//        LogUtil.info("传化武圣余额：" + balanceThree.toString());
//        LogUtil.info("得仕智圣余额：" + balanceFour.toString());
//        LogUtil.info("得仕信圣余额：" + balanceFive.toString());
        LogUtil.info("招商九歌余额：" + balanceEight.toString());
        LogUtil.info("招商信圣余额：" + balanceNine.toString());
        LogUtil.info("招商智圣余额：" + balanceTen.toString());
//        LogUtil.info("招商法圣余额：" + balanceEleven.toString());
        LogUtil.info("招商明圣余额：" + mingShengBanlance.toString());
        LogUtil.info("招商美圣余额：" + meiShengBalance.toString());
        LogUtil.info("招商秀圣余额：" + xiuShengBalance.toString());
        LogUtil.info("招商英圣余额：" + yingShengBalance.toString());
        //比较金额，如果不能低于100万，如果低于100万则要发消息预警。(发送给胡刚和cindy还有夏姐)
        BigDecimal minimum = new BigDecimal("1000000");
        String info = "";
//        if(balanceOne.compareTo(minimum) < 1){
//            info += "得仕九歌账号余额:" + balanceOne.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
//        }
//        if(balanceTwo.compareTo(minimum) < 1){
//            info += "得仕武圣账号余额:" + balanceTwo.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
//        }
//        if(balanceThree.compareTo(minimum) < 1){
//            info += "传化武圣账号余额:" + balanceThree.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
//        }
//        if(balanceFour.compareTo(minimum) < 1){
//            info += "得仕智圣账号余额:" + balanceFour.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
//        }
//        if(balanceFive.compareTo(minimum) < 1){
//            info += "得仕信圣账号余额:" + balanceFive.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
//        }
        if (balanceEight.compareTo(minimum) < 1) {
            info += "招商九歌账号余额:" + balanceEight.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
        }
        if (balanceNine.compareTo(minimum) < 1) {
            info += "招商信圣账号余额:" + balanceNine.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
        }
        if (balanceTen.compareTo(minimum) < 1) {
            info += "招商智圣账号余额:" + balanceTen.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
        }
//        if (balanceEleven.compareTo(minimum) < 1) {
//            info += "招商法圣账号余额:" + balanceEleven.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
//        }
        if (mingShengBanlance.compareTo(minimum) < 1) {
            info += "招商明圣账号余额:" + mingShengBanlance.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "\n";
        }
        if (meiShengBalance.compareTo(minimum) < 1) {
            info += "招商美圣账号余额:" + meiShengBalance.setScale(2, BigDecimal.ROUND_HALF_UP) + "\n";
        }
        if (xiuShengBalance.compareTo(minimum) < 1) {
            info += "招商秀圣账号余额:" + xiuShengBalance.setScale(2, BigDecimal.ROUND_HALF_UP) + "\n";
        }
        if (mingShengBanlance.compareTo(minimum) < 1) {
            info += "招商英圣账号余额:" + yingShengBalance.setScale(2, BigDecimal.ROUND_HALF_UP) + "\n";
        }

        if (StringUtil.isNotEmpty(info)) {
            if (!wxMessageService.balanceInsufficientNotice(info, type)) {
                LogUtil.error("余额低于100万消息提醒发送失败！");
            }
        } else {
            LogUtil.info("余额都大于100万不需要消息提醒！");
        }
    }

    public BigDecimal queryDeShiJiuGeBalance() {
        //查询得仕九歌账户余额
        BigDecimal balanceOne = new BigDecimal("0");
        SmartResult smartResult1 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDayQueryMerchantBalanceUrl() + "?daysMerchantId=1",
                SmartResult.class);
        if (smartResult1 != null && smartResult1.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult1.toJson().getJSONObject("object");
            if (null != object) {
                String transInfo = StringEscapeUtils.unescapeJava(object.getString("transInfo"));
                JSONObject info = JSONObject.parseObject(transInfo);
                //获取余额
                balanceOne = balanceOne.add(new BigDecimal(info.getString("balance")));
            } else {
                LogUtil.error("查询得仕九歌账户余额失败！返回：" + smartResult1.toString());
            }
        } else {
            if (null == smartResult1) {
                LogUtil.error("查询得仕九歌账户余额返回为空！");
            } else {
                LogUtil.error("查询得仕九歌账户余额失败！返回：" + smartResult1.toString());
            }
        }
        return balanceOne;
    }

    public BigDecimal queryDeShiWuShengBalance() {
        //查询得仕武圣账户余额
        BigDecimal balanceTwo = new BigDecimal("0");
        SmartResult smartResult2 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDayQueryMerchantBalanceUrl() + "?daysMerchantId=2",
                SmartResult.class);
        if (smartResult2 != null && smartResult2.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult2.toJson().getJSONObject("object");
            if (null != object) {
                String transInfo = StringEscapeUtils.unescapeJava(object.getString("transInfo"));
                JSONObject info = JSONObject.parseObject(transInfo);
                //获取余额
                balanceTwo = balanceTwo.add(new BigDecimal(info.getString("balance")));
            } else {
                LogUtil.error("查询得仕武圣账户余额失败！返回：" + smartResult2.toString());
            }
        } else {
            if (null == smartResult2) {
                LogUtil.error("查询得仕武圣账户余额返回为空！");
            } else {
                LogUtil.error("查询得仕武圣账户余额失败！返回：" + smartResult2.toString());
            }
        }
        return balanceTwo;
    }

    public BigDecimal queryChuanHuaWuShengBalance() {
        //查询传化武圣账户余额
        BigDecimal balanceThree = new BigDecimal("0");
        SmartResult smartResult3 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getTransferQueryMerchantBalanceUrl() + "?paymentMerchant=4", SmartResult.class);
        if (smartResult3 != null && smartResult3.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult3.toJson().getJSONObject("object");
            if (null != object) {
                JSONObject data = object.getJSONObject("data");
                //获取余额
                balanceThree = balanceThree.add(new BigDecimal(data.getString("balance")));
            } else {
                LogUtil.error("查询传化武圣账户余额失败！返回：" + smartResult3.toString());
            }
        } else {
            if (null == smartResult3) {
                LogUtil.error("查询传化武圣账户余额返回为空！");
            } else {
                LogUtil.error("查询传化武圣账户余额失败！返回：" + smartResult3.toString());
            }
        }
        return balanceThree;
    }

    public BigDecimal queryChuanHuaZhiShengBalance() {
        //查询传化智圣账户余额
        BigDecimal balanceThree = new BigDecimal("0");
        SmartResult smartResult3 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getTransferQueryMerchantBalanceUrl() + "?paymentMerchant=12", SmartResult.class);
        if (smartResult3 != null && smartResult3.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult3.toJson().getJSONObject("object");
            if (null != object) {
                JSONObject data = object.getJSONObject("data");
                //获取余额
                balanceThree = balanceThree.add(new BigDecimal(data.getString("balance")));
            } else {
                LogUtil.error("查询传化智圣账户余额失败！返回：" + smartResult3.toString());
            }
        } else {
            if (null == smartResult3) {
                LogUtil.error("查询传化智圣账户余额返回为空！");
            } else {
                LogUtil.error("查询传化智圣账户余额失败！返回：" + smartResult3.toString());
            }
        }
        return balanceThree;
    }

    public BigDecimal queryChuanHuaJiuGeBalance() {
        //查询传化智圣账户余额
        BigDecimal balanceThree = new BigDecimal("0");
        SmartResult smartResult3 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getTransferQueryMerchantBalanceUrl() + "?paymentMerchant=13", SmartResult.class);
        if (smartResult3 != null && smartResult3.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult3.toJson().getJSONObject("object");
            if (null != object) {
                JSONObject data = object.getJSONObject("data");
                //获取余额
                balanceThree = balanceThree.add(new BigDecimal(data.getString("balance")));
            } else {
                LogUtil.error("查询传化九歌账户余额失败！返回：" + smartResult3.toString());
            }
        } else {
            if (null == smartResult3) {
                LogUtil.error("查询传化智九歌户余额返回为空！");
            } else {
                LogUtil.error("查询传化智九歌户余额失败！返回：" + smartResult3.toString());
            }
        }
        return balanceThree;
    }


    public BigDecimal queryDeShiZhiShengBalance() {
        //查询得仕智圣账户余额
        BigDecimal balanceFour = new BigDecimal("0");
        SmartResult smartResult4 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDayQueryMerchantBalanceUrl() + "?daysMerchantId=3",
                SmartResult.class);
        if (smartResult4 != null && smartResult4.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult4.toJson().getJSONObject("object");
            if (null != object) {
                String transInfo = StringEscapeUtils.unescapeJava(object.getString("transInfo"));
                JSONObject info = JSONObject.parseObject(transInfo);
                //获取余额
                balanceFour = balanceFour.add(new BigDecimal(info.getString("balance")));
            } else {
                LogUtil.error("查询得仕智圣账户余额失败！返回：" + smartResult4.toString());
            }
        } else {
            if (null == smartResult4) {
                LogUtil.error("查询得仕智圣账户余额返回为空！");
            } else {
                LogUtil.error("查询得仕智圣账户余额失败！返回：" + smartResult4.toString());
            }
        }
        return balanceFour;
    }

    public BigDecimal queryDeShiXinShengBalance() {
        //查询得仕信圣账户余额
        BigDecimal balanceFive = new BigDecimal("0");
        SmartResult smartResult5 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDayQueryMerchantBalanceUrl() + "?daysMerchantId=6",
                SmartResult.class);
        if (smartResult5 != null && smartResult5.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult5.toJson().getJSONObject("object");
            if (null != object) {
                String transInfo = StringEscapeUtils.unescapeJava(object.getString("transInfo"));
                JSONObject info = JSONObject.parseObject(transInfo);
                //获取余额
                balanceFive = balanceFive.add(new BigDecimal(info.getString("balance")));
            } else {
                LogUtil.error("查询得仕信圣账户余额失败！返回：" + smartResult5.toString());
            }
        } else {
            if (null == smartResult5) {
                LogUtil.error("查询得仕信圣账户余额返回为空！");
            } else {
                LogUtil.error("查询得仕信圣账户余额失败！返回：" + smartResult5.toString());
            }
        }
        return balanceFive;
    }

    public BigDecimal queryChuanHuaXinShengBalance() {
        //查询传化信圣账户余额
        BigDecimal balanceSix = new BigDecimal("0");
        SmartResult smartResult6 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getTransferQueryMerchantBalanceUrl() + "?paymentMerchant=5", SmartResult.class);
        if (smartResult6 != null && smartResult6.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult6.toJson().getJSONObject("object");
            if (null != object) {
                JSONObject data = object.getJSONObject("data");
                if (data != null) {
                    //获取余额
                    balanceSix = balanceSix.add(new BigDecimal(data.getString("balance")));
                }
            } else {
                LogUtil.error("查询传化信圣账户余额失败！返回：" + smartResult6.toString());
            }
        } else {
            if (null == smartResult6) {
                LogUtil.error("查询传化信圣账户余额返回为空！");
            } else {
                LogUtil.error("查询传化信圣账户余额失败！返回：" + smartResult6.toString());
            }
        }
        return balanceSix;
    }

    public BigDecimal queryDeShiYingShengBalance() {
        //查询得仕英圣账户余额
        BigDecimal balanceSeven = new BigDecimal("0");
        SmartResult smartResult7 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDayQueryMerchantBalanceUrl() + "?daysMerchantId=8",
                SmartResult.class);
        if (smartResult7 != null && smartResult7.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult7.toJson().getJSONObject("object");
            if (null != object) {
                String transInfo = StringEscapeUtils.unescapeJava(object.getString("transInfo"));
                JSONObject info = JSONObject.parseObject(transInfo);
                //获取余额
                balanceSeven = balanceSeven.add(new BigDecimal(info.getString("balance")));
            } else {
                LogUtil.error("查询得仕英圣账户余额失败！返回：" + smartResult7.toString());
            }
        } else {
            if (null == smartResult7) {
                LogUtil.error("查询得仕英圣账户余额返回为空！");
            } else {
                LogUtil.error("查询得仕英圣账户余额失败！返回：" + smartResult7.toString());
            }
        }
        return balanceSeven;
    }

    public BigDecimal queryZhaoShangJiuGeBalance() {
        //查询招商九歌账户余额
        BigDecimal balanceEight = new BigDecimal("0");
        SmartResult smartResult8 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryBalanceUrl() + "?merchantId=7",
                SmartResult.class);
        if (smartResult8 != null && smartResult8.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult8.toJson().getJSONObject("object");
            if (null != object) {
                //获取余额
                balanceEight = balanceEight.add(new BigDecimal(object.getString("avlblv")));
            } else {
                LogUtil.error("查询招商九歌账户余额失败！返回：" + smartResult8.toString());
            }
        } else {
            if (null == smartResult8) {
                LogUtil.error("查询招商九歌账户余额返回为空！");
            } else {
                LogUtil.error("查询招商九歌账户余额失败！返回：" + smartResult8.toString());
            }
        }
        return balanceEight;
    }

    public BigDecimal queryZhaoShangXinShengBalance() {
        //查询招商信圣账户余额
        BigDecimal balanceNine = new BigDecimal("0");
        SmartResult smartResult9 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryBalanceUrl() + "?merchantId=9",
                SmartResult.class);
        if (smartResult9 != null && smartResult9.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult9.toJson().getJSONObject("object");
            if (null != object) {
                //获取余额
                balanceNine = balanceNine.add(new BigDecimal(object.getString("avlblv")));
            } else {
                LogUtil.error("查询招商信圣账户余额失败！返回：" + smartResult9.toString());
            }
        } else {
            if (null == smartResult9) {
                LogUtil.error("查询招商信圣账户余额返回为空！");
            } else {
                LogUtil.error("查询招商信圣账户余额失败！返回：" + smartResult9.toString());
            }
        }
        return balanceNine;
    }

    public BigDecimal queryZhaoShangBalance(int merchantId) {
        //查询招商账户余额
        BigDecimal balanceTen = new BigDecimal("0");
        SmartResult smartResult10 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryBalanceUrl() + "?merchantId=" + merchantId,
                SmartResult.class);
        if (smartResult10 != null && smartResult10.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult10.toJson().getJSONObject("object");
            if (null != object) {
                //获取余额
                balanceTen = balanceTen.add(new BigDecimal(object.getString("avlblv")));
            } else {
                log.error("查询招商账户:{}余额失败！返回：{}", merchantId, smartResult10.toString());
            }
        } else {
            if (null == smartResult10) {
                log.error("查询招商账户:{}余额返回为空！", merchantId);
            } else {
                log.error("查询招商账户:{}余额失败！返回：{}", merchantId, smartResult10.toString());
            }
        }
        return balanceTen;
    }

    public BigDecimal queryZhaoShangZhiShengBalance() {
        //查询招商智圣账户余额
        BigDecimal balanceTen = new BigDecimal("0");
        SmartResult smartResult10 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryBalanceUrl() + "?merchantId=10",
                SmartResult.class);
        if (smartResult10 != null && smartResult10.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult10.toJson().getJSONObject("object");
            if (null != object) {
                //获取余额
                balanceTen = balanceTen.add(new BigDecimal(object.getString("avlblv")));
            } else {
                LogUtil.error("查询招商智圣账户余额失败！返回：" + smartResult10.toString());
            }
        } else {
            if (null == smartResult10) {
                LogUtil.error("查询招商智圣账户余额返回为空！");
            } else {
                LogUtil.error("查询招商智圣账户余额失败！返回：" + smartResult10.toString());
            }
        }
        return balanceTen;
    }

    public BigDecimal queryZhaoShangFaShengBalance() {
        //查询招商法圣账户余额
        BigDecimal balanceEleven = new BigDecimal("0");
        SmartResult smartResult11 = new RestTemplate().getForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryBalanceUrl() + "?merchantId=11",
                SmartResult.class);
        if (smartResult11 != null && smartResult11.getState() == StatusMsg.StatusMsg_100.getState()) {
            JSONObject object = smartResult11.toJson().getJSONObject("object");
            if (null != object) {
                //获取余额
                balanceEleven = balanceEleven.add(new BigDecimal(object.getString("avlblv")));
            } else {
                LogUtil.error("查询招商法圣账户余额失败！返回：" + smartResult11.toString());
            }
        } else {
            if (null == smartResult11) {
                LogUtil.error("查询招商法圣账户余额返回为空！");
            } else {
                LogUtil.error("查询招商法圣账户余额失败！返回：" + smartResult11.toString());
            }
        }
        return balanceEleven;
    }

    /**
     * 查询支付宝余额
     *
     * @return
     */
    public BigDecimal queryAlipayAccountQuery(int principalEnumId) {
        //principalEnumId转换对应的pay包中的支付宝配置 目前是一样的
        //查询各支付主体的余额
        BigDecimal balanceEleven = new BigDecimal("0");
        AlipayAccountQueryFormBean alipayAccountQueryFormBean = new AlipayAccountQueryFormBean();
        alipayAccountQueryFormBean.setPaymentMerchant(principalEnumId);
        SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getAliPayAccountQueryUrl(),
                alipayAccountQueryFormBean, SmartResult.class);
        if (smartResult != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
            AlipayDataBillBalanceQueryResponse queryResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
                    new TypeReference<AlipayDataBillBalanceQueryResponse>() {
                    });
            String availableAmount = queryResult.getAvailableAmount();
            if (null != availableAmount) {
                balanceEleven = new BigDecimal(availableAmount);
            }
        }
        return balanceEleven;
    }
    /**
     * 查询平安余额
     *
     * @return
     */
    public BigDecimal queryPinganAccountQuery(int merchantId) {
        //查询各支付主体的余额
        BigDecimal balanceEleven = new BigDecimal("0");
        PinganQueryFormBean pinganQueryFormBean = new PinganQueryFormBean();
        pinganQueryFormBean.setPaymentMerchant(merchantId);
        SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getPinganBalanceQueryUrl(),
                pinganQueryFormBean, SmartResult.class);
        if (smartResult != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
            BalanceQuery queryResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
                    new TypeReference<BalanceQuery>() {
                    });
            String availableAmount = queryResult.getBalance();
            if (null != availableAmount) {
                balanceEleven = new BigDecimal(availableAmount);
            }
        }
        return balanceEleven;
    }
}
